//
//  PictureSelectorCollectionViewController.swift
//  WeChat
//
//  Created by 梁迪 on 15/12/24.
//  Copyright © 2015年 梁迪. All rights reserved.
//

import UIKit
import SnapKit

private let reuseIdentifier = "Cell"
private let rowCount:CGFloat = 3
private let margin:CGFloat = 5
private let maxImageCount = 4

class PictureSelectorCollectionViewController: UICollectionViewController {
     var imageList = [UIImage]()
    
    init(){
        
        let itemW = (screenW - (rowCount + 1) * margin ) / rowCount
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: itemW, height: itemW)
        layout.minimumInteritemSpacing = margin
        layout.minimumLineSpacing = margin
        
        //设置组建局
        layout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)
        super.init(collectionViewLayout: layout)
        
        
        collectionView?.backgroundColor = UIColor.whiteColor()
        
        
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

       
        self.collectionView!.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    
    // MARK: UICollectionViewDataSource

//    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
//        // #warning Incomplete implementation, return the number of sections
//        return 0
//    }


    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
//        return 9
        
        let delta = imageList.count == maxImageCount ? 0:1
        return imageList.count + delta
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSelectorCell
//    cell.backgroundColor = UIColor.randomColor()
        
        cell.delegate = self
        
        if indexPath.item == imageList.count{
            cell.image = nil
        }else{
            
            cell.image = imageList[indexPath.item]
        }
        
        
        return cell
    }

   

}



extension PictureSelectorCollectionViewController:PictureSelectorCellDelegate{
    func userWillDeletePicture(cell: PictureSelectorCell) {
        if let index = collectionView?.indexPathForCell(cell){
            imageList.removeAtIndex(index.item)
            collectionView?.reloadData()
            
        }
        
        
        
    }
    
    func userWillChosePicture(cell:PictureSelectorCell) {
        
        if cell.image != nil{
            
//            print("已经显示图片了,不要再点击了")
            return
        }
        
        let picker = UIImagePickerController()
        presentViewController(picker, animated: true, completion: nil)
        picker.delegate = self
        
        
        
        
    }
    
    
}

extension PictureSelectorCollectionViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        imageList.append(image)
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
        
        
        
        
    }
    
    
    
    
    
    
    
    
}



//--------------------------------------------------

@objc protocol PictureSelectorCellDelegate:NSObjectProtocol{
    optional func userWillChosePicture(cell:PictureSelectorCell)
    optional func userWillDeletePicture(cell:PictureSelectorCell)
    
   
}




class PictureSelectorCell: UICollectionViewCell {
    
    var image:UIImage? {
        didSet{
            deleteBtn.hidden = image == nil
            
            addBtn.setImage(image, forState: .Normal)
        }
        
        
    }
    
    
    
    @objc private func addBtnDidClick(){
        
        delegate?.userWillChosePicture?(self)
        
    }
    @objc private func deleteBtnDidClick(){
        delegate?.userWillDeletePicture?(self)
        
    }
    
    
    weak var delegate:PictureSelectorCellDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        
        addBtn.imageView?.contentMode = .ScaleAspectFill
    
        contentView.addSubview(addBtn)
            contentView.addSubview(deleteBtn)
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
            
        }
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(addBtn.snp_top)
            make.right.equalTo(addBtn.snp_right)
            
        }
        
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnDidClick", forControlEvents: .TouchUpInside)
        
    }
    
    private lazy var deleteBtn:UIButton = UIButton(imageName: nil, backImageName: "compose_photo_close")
    private lazy var addBtn:UIButton = UIButton(imageName: nil, backImageName: "compose_pic_add")
    
}

